/*
 * This file is part of Cadmium.
 * Copyright (C) 2007-2010 Xavier Clerc.
 *
 * Cadmium is free software; you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * Cadmium is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package fr.x9c.cadmium.primitives.cadmiumxml;

import org.w3c.dom.Attr;
import org.w3c.dom.CDATASection;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.Text;

import fr.x9c.cadmium.kernel.Block;
import fr.x9c.cadmium.kernel.CodeRunner;
import fr.x9c.cadmium.kernel.Fail;
import fr.x9c.cadmium.kernel.Primitive;
import fr.x9c.cadmium.kernel.PrimitiveProvider;
import fr.x9c.cadmium.kernel.Value;
import fr.x9c.cadmium.primitives.cadmium.Cadmium;

/**
 * This class provides the primitives for tree conversion.
 *
 * @author <a href="mailto:cadmium@x9c.fr">Xavier Clerc</a>
 * @version 1.0
 * @since 1.0
 */
@PrimitiveProvider
public final class Trees {

    /**
     * No instance of this class.
     */
    private Trees() {
    } // end empty constructor

    /**
     * Converts a document into a simplified representation.
     * @param ctxt context
     * @param document document to convert
     * @return passed document as a <i>CadmiumXML.Tree.t</i> instance
     * @throws Fail.Exception if an error occurs during conversion
     */
    @Primitive
    public static Value cadmiumxml_tree_of_document(final CodeRunner ctxt,
                                                    final Value document)
        throws Fail.Exception {
        try {
            final Document doc = (Document) document.asBlock().asCustom();
            return encodeNode(doc.getDocumentElement());
        } catch (final Exception e) {
            Cadmium.fail(ctxt, e);
            return Value.UNIT; // never reached
        } // end try/catch
    } // end method 'cadmiumxml_tree_of_document(CodeRunner, Value)'

    /**
     * Encodes a node.
     * @param n node to encode - should not be <tt>null</tt>
     * @return passed node as a <i>CadmiumXML.Tree.t</i> instance
     * @throws Fail.Exception if an error occurs during encoding
     */
    private static Value encodeNode(final Node n) throws Fail.Exception {
        assert n != null : "null n";
        if (n instanceof Element) {
            final Element e = (Element) n;
            final Value tag = Value.createFromBlock(Block.createString(e.getTagName()));
            Value attributes = Value.EMPTY_LIST;
            final NamedNodeMap al = e.getAttributes();
            for (int i = al.getLength() - 1; i >= 0; i--) {
                final Attr a = (Attr) al.item(i);
                final Block couple = Block.createBlock(0,
                                                       Value.createFromBlock(Block.createString(a.getName())),
                                                       Value.createFromBlock(Block.createString(a.getValue())));
                final Block b = Block.createBlock(Block.TAG_CONS,
                                                  Value.createFromBlock(couple),
                                                  attributes);
                attributes = Value.createFromBlock(b);
            } // end for
            Value children = Value.EMPTY_LIST;
            final NodeList cl = e.getChildNodes();
            for (int i = cl.getLength(); i >= 0; i--) {
                final Node c = cl.item(i);
                if ((c instanceof Element)
                    || (c instanceof CDATASection)
                    || (c instanceof Text)) {
                    final Block b = Block.createBlock(Block.TAG_CONS,
                                                      encodeNode(c),
                                                      children);
                    children = Value.createFromBlock(b);
                } // end if
            } // end for
            final Block res = Block.createBlock(0, tag, attributes, children);
            return Value.createFromBlock(Block.createBlock(0,
                                                           Value.createFromBlock(res)));
        } else if (n instanceof CDATASection) {
            final String d = ((CDATASection) n).getData();
            final Value res = Value.createFromBlock(Block.createString(d));
            return Value.createFromBlock(Block.createBlock(1, res));
        } else if (n instanceof Text) {
            final String d = ((Text) n).getData();
            final Value res = Value.createFromBlock(Block.createString(d));
            return Value.createFromBlock(Block.createBlock(2, res));
        } else {
            Fail.failWith("unknown node type");
            return Value.UNIT; // never reached
        } // end if/elsif/else
    } // end method 'encodeNode(Node)'

} // end class 'Trees'
